const express = require("express");
const db = require("./../libs/DBhelper");
const md5 = require("md5");
const fs = require("fs");
const path = require("path");

let apiRouter = express.Router();

//注册模块
apiRouter.post("/reg", (request, response, next) => {
    //1.处理图片上传的文件


    //把路径,用户名,密码..保存到数据库

    //准备sql语句
    let sql = "INSERT INTO `users` (`u_name`,`u_pwd`,`u_address`,`u_email`) VALUES(?,?,?,?);";
    //准备参数
    let params = [
        request.body.u_name,
        md5(md5(request.body.u_pwd) + require("./../libs/Configs").keys), //使用MD5加密
        request.body.u_address,
        request.body.u_email,
    ]

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "sql语有问题",
                status: -2
            });
            return;
        }
        if (result.affectedRows >= 1) {
            response.json({
                msg: "恭喜,注册成功",
                status: 1
            })
        } else {
            response.json({
                msg: "注册失败",
                status: -1
            });
        }

    })

})

//登录模块
apiRouter.post("/login", (request, response, next) => {

    let sql = "SELECT `u_id`,`u_name`,`u_address`,`u_email` ";
    sql = sql.concat("FROM users WHERE  u_status=1 AND u_name=? AND u_pwd=? ;");

    let params = [
        request.body.u_name,
        md5(md5(request.body.u_pwd) + require("./../libs/Configs").keys), //md5 2次加密
    ]

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "登录失败",
                err: err.message
            })

            return;
        }

        if (result.length >= 1) {
            request.session["users"]="开心就好",
            response.json({
                msg: "登录成功",
                status: 1,
                data: result[0],
            })
        } else {
            response.json({
                msg: "登录失败,用户名或密码错误",
                status: -1
            })
        }
    })
})
//产品列表
apiRouter.get("/goods", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/list.json", {
        encoding: "utf-8"
    }).toString();
    response.end(goodsStr);
})
//产品列表
apiRouter.get("/goodsinfo/:id", (request, response, next) => {
    var goodsStr = fs.readFileSync("./data/list.json", {
        encoding: "utf-8"
    }).toString();

    console.log(request.params.id)

    var resultObj = JSON.parse(goodsStr).filter((el) => {
        return el.p_id == request.params.id
    })

    response.json(resultObj);
})
// ------------------------------------------------------------------
//加入购物车接口
apiRouter.post("/addcart", (request, response, next) => {
    //异常捕获
    try {
        //1.更加用户名和商品id 查询 该数据是否存在
        let querySelect = "SELECT * FROM `carts` WHERE  u_id=? AND p_id=?;";
        let queryPrams = [
            request.body.u_id,
            request.body.p_id
        ]
        console.log(queryPrams);
        db.exec(querySelect, queryPrams, (err, queryResult) => {
            // console.log("查询",queryResult)
            //查询返回结果,结果是一个数组 length属性
            if (queryResult.length >= 1) {
                var updateSql = "UPDATE carts SET p_number=p_number+? , p_total=p_number*p_price WHERE u_id=? AND p_id=? ;";
                let updatePrams = [
                    request.body.p_number,
                    request.body.u_id,
                    request.body.p_id
                ]
                db.exec(updateSql, updatePrams, (err, updateReulst) => {
                    // console.log("修改",updateReulst);
                    if (updateReulst.affectedRows == 1) {
                        response.json({
                            msg: "加入购物成功u",
                            status: 1
                        })
                    } else {
                        response.json({
                            msg: "加入购物车失败u",
                            status: -1
                        })
                    }
                });
            } else {
                // 加入到数据库,我老人家,需要准备哪些参数?
                // 商品id,用户名id,商品名称,商品价格,商品数量,商品图片 ,商品描述

                let sql = "INSERT INTO carts (u_id ,p_id, p_name , p_price , p_number , p_img , p_size,p_total)VALUES(?,?,?,?,?,?,?,?);";

                let params = [
                    request.body.u_id,
                    request.body.p_id,
                    request.body.p_name,
                    request.body.p_price,
                    request.body.p_number,
                    request.body.p_img_index,
                    request.body.p_size,
                    request.body.p_price * request.body.p_number
                ]
                db.exec(sql, params, (err, result) => {
                    if (err) {
                        console.log(err.message)
                        response.json({
                            msg: "加入购物车失败i",
                            status: -1,
                            err: err.message
                        })
                    }
                    // console.log("添加",result)
                    if (result.affectedRows >= 1) {
                        response.json({
                            msg: "加入购物成功i",
                            status: 1
                        })
                    }
                })
            }
        });
    } catch (err) {
        response.json({
            msg: "加入失败",
            err: err.message,
            status: -2
        })

    }

})

// 获取物品清单接口
apiRouter.get("/getcarts", (request, response, next) => {

    let sql = " SELECT * FROM `carts` WHERE  u_id=? ;";
    let params = [
        request.query.u_id
    ]

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "拉取购物车列表失败",
                status: -2,
                err: err.message
            });
            return;
        }
        response.json({
            msg: "拉取成功",
            status: 1,
            data: result
        });
    })
})

//购物列表对某个产品  加加减减
apiRouter.post("/modify", (request, response, next) => {

    var updateSql = "UPDATE carts SET p_number=?, p_total=p_number*p_price WHERE c_id=? ;";
    let updatePrams = [
        request.body.p_number,
        request.body.c_id,
    ]

    db.exec(updateSql, updatePrams, (err, updateReulst) => {

        if (err) {
            response.json({
                msg: "加入购物车失败u",
                status: -1,
                err: err.message
            })

            return;
        }

        if (updateReulst.affectedRows == 1) {
            response.json({
                msg: "加入购物成功u",
                status: 1
            })
        }
    });
})

// 购物列表删除物品
apiRouter.post("/delete", (request, response, next) => {
    let sql = "DELETE FROM carts WHERE  c_id=? ;";
    let params = [request.body.c_id];

    db.exec(sql, params, (err, result) => {
        if (err) {
            response.json({
                msg: "删除失败",
                status: -2,
                err: err.message
            })
            return;
        }
        if (result.affectedRows == 1) {
            //给后台的反馈
            console.log(`已删除${params.c_id}`);
            response.json({
                msg: "删除成功",
                status: 1
            })
        } else {
            response.json({
                msg: "删除失败"
            })
        }
    })
})

//暴露api路由对象
module.exports = {
    apiRouter
}